Examples of drawingΒΆ
Note
- turtle.forward(distance):
Moves the turtle forward (in the direction the turtle is facing) the distance indicated (in pixels). Draws a line if the pen is down, not if the pen is up.
- turtle.left(degrees):
Turns the direction that the turtle is facing left (counterclockwise) by the amount indicated (in degrees).
import turtle
import time
import math
def draw_letter_s(t, distance, degrees, sleep_time):
t.shape('turtle')
t.forward(distance) # move forward
t.left(degrees) # turn by "degrees"
time.sleep(sleep_time)
t.forward(distance)
t.left(degrees)
time.sleep(sleep_time)
t.forward(distance)
t.right(degrees)
time.sleep(sleep_time)
t.forward(distance)
t.right(degrees)
time.sleep(sleep_time)
t.forward(distance)
# def draw_square(t, side_length):
# for i in range(4):
# t.forward(side_length)
# t.left(90)
def draw_polygon(t, side_length, num_sides):
turn_angle = 360 / num_sides
for i in range(num_sides):
t.forward(side_length)
t.left(turn_angle)
def draw_circle(t, radius):
circumference = 2 * 3.1415 * radius # 2 * Pi * R
side_length = circumference / 360
draw_polygon(t, side_length, 360)
def main():
# Create a screen
canvas = turtle.Screen()
canvas.bgcolor('lightblue')
# Create a turtle
t = turtle.Turtle()
t.reset()
# Draw polygon
t.goto(0, 0)
draw_polygon(t, 4, 4)
# Draw letter S
t.pensize(10)
t.color("blue")
t.up()
t.goto(-50, -100)
t.down()
draw_letter_s(t, 100, 90, 0)
# Draw 3 squares
t.color("red")
for i in range(0, 3):
t.up()
t.pensize((i + 1)* 2)
t.goto(-150 - i * 20, -150 - i * 20)
t.down()
draw_polygon(t, 300 + i * 40, 4)
# Draw polygon
t.pensize(4)
t.color("green")
t.up()
t.goto(-150, -(3/4 * 300**2) ** (1/2))
# r = 300 * math.sin(math.radians(45)) # (300 * (2**(1/2)/2)))
t.down()
draw_polygon(t, 300, 6)
# Draw circle
t.pensize(4)
t.color("yellow")
t.up()
t.goto(0, -300)
t.down()
draw_circle(t, 300)
t.ht()
canvas.exitonclick()
if __name__ == '__main__':
main()
# mainloop()
Shape |
Sides |
range() |
Angle |
---|---|---|---|
Triangle |
3 |
3 |
360/3 = 120 |
Square |
4 |
4 |
360/4 = 90 |
Octagon |
8 |
8 |
360/8 = 45 |